package com.whut.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whut.common.BaseContext;
import com.whut.entity.Admin;
import com.whut.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @ClassName:AdminController
 * @Description:管理员类
 * @Author:liumengying
 * @Date: 2022/8/5 14:24
 * Version v1.0
 */
@RestController
@Slf4j
//@RequestMapping("/backend/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 管理端登录
     * @param request
     * @return
     */
    @PostMapping("backend/admin/login.do")
    public String login(HttpServletRequest request){
        Admin admin=new Admin();
        admin.setLoginTime(LocalDateTime.now());
        String userName=request.getParameter("username");
        String password=request.getParameter("password");
        log.info("进入后台登录函数，获取的数据：{},{}",userName,password);
        //1.将页面提交的密码password进行md5加密处理

//        password= DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        //创建MyBatis-Plus的查询包装器
        final LambdaQueryWrapper<Admin> queryWrapper=new LambdaQueryWrapper<>();
        //where username='admin'
        queryWrapper.eq(Admin::getUsername,userName);
        final Admin emp =adminService.getOne(queryWrapper);
        admin.setId(emp.getId());  //设置ID
        //3.如果没有返回登陆失败
        if(emp == null){
            return  "登录失败";
        }
        //4.密码比对，失败返回
        if(!emp.getPassword().equals(password)){
            return  "登陆失败";
        }

        //5.登录成功，将员工id存入到session并返回登陆成功结果
//        adminService.updateById(admin);
        request.getSession().setAttribute("Admin",emp.getId());
        BaseContext.setCurrentId(emp.getId());
        log.info("用户{}登录成功",userName);
        return "登陆成功";
    }

    @PostMapping("/admin/logout.do")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("Admin");
//        request.getSession().invalidate();
        return "success";
    }
}
